package com.takeoutsystem.interceptor;

import com.takeoutsystem.bean.AdminAccount;
import com.takeoutsystem.service.AdminAccountService;
import com.takeoutsystem.support.CookieUtil;
import com.takeoutsystem.support.EnCryptAndDeCryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证管理员登录状态拦截器
 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Autowired
    AdminAccountService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //session验证
        AdminAccount user =(AdminAccount) request.getSession().getAttribute("user");
        if(user!=null) {
            //session验证成功
            return true;
        }else{
            //cookie验证
            String code= CookieUtil.getValueByKey("autoLogin",request);
            if(code==null){code="";}
            try{
                code=EnCryptAndDeCryptUtil.decryptBase64(code);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(!"".equals(code)){
                String[] strs=code.split("_");
                AdminAccount account=new AdminAccount();
                account.setUsername(strs[0]);
                account.setPassword(strs[1]);
                if(service.checkLogin(account)){
                    request.getSession().setAttribute("user",account);
                    request.getSession().setAttribute("username",strs[0]);
                    //cookie验证成功
                    return true;
                }
            }
            //session和cookie验证失败，跳转登录页
            request.setAttribute("failMsg","请先登录");
            RequestDispatcher dispatcher=request.getRequestDispatcher("/admin/login");
            dispatcher.forward(request,response);
            return false;
        }

    }
}
